//
//  UIImage+DFExtension.m
//  Pods
//
//  Created by rujia chen on 17/5/12.
//
//

#import "UIImage+DFExtension.h"

@implementation UIImage (DFExtension)

+ (UIImage *)df_imageWithColor:(UIColor *)color size:(CGSize)size alpha:(float)alpha {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetAlpha(context, alpha);
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

- (UIImage *)df_tintedImageWithColor:(UIColor*)color {
    return [self df_tintedImageWithColor:color alpha:1.0f];
}

- (UIImage *)df_tintedImageWithColor:(UIColor*)color alpha:(CGFloat)alpha {
    CGRect rect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
    return [self df_tintedImageWithColor:color rect:rect alpha:alpha];
}

- (UIImage *)df_tintedImageWithColor:(UIColor*)color rect:(CGRect)rect {
    return [self df_tintedImageWithColor:color rect:rect alpha:1.0f];
}

- (UIImage *)df_tintedImageWithColor:(UIColor*)color rect:(CGRect)rect alpha:(CGFloat)alpha {
    CGRect imageRect = CGRectMake(0, 0, self.size.width, self.size.height);
    
    UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, self.scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [self drawInRect:imageRect];
    
    CGContextSetFillColorWithColor(ctx, [color CGColor]);
    CGContextSetAlpha(ctx, alpha);
    CGContextSetBlendMode(ctx, kCGBlendModeSourceAtop);
    CGContextFillRect(ctx, rect);
    
    CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
    UIImage *darkImage = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    
    UIGraphicsEndImageContext();
    
    return darkImage;
}

@end
